package shiqi.db.user;

import shiqi.db.Db;
import shiqi.model.User;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @program: ascend
 * @description: 用map存储user的数据库
 * @author: shiqi
 * @create: 2022-03-17 19:38
 **/
public class MapUserDb implements Db<User, Long> {

    private Map<String, User> dataSource = new HashMap<>();

    @Override
    public void initData() {
        User shiqi = new User(1L, "shiqi", "a123456");
        User ljh = new User(2L, "ljh", "a123456");
        dataSource.put(shiqi.getUserId().toString(), shiqi);
        dataSource.put(ljh.getUserId().toString(), ljh);
    }

    @Override
    public User search(User user) throws IllegalAccessException {
        User result = null;
        // 有传id就直接根据id搜索
        if (user.getUserId() != null) {
            return dataSource.get(result.getUserId().toString());
        }
        // 没有id直接遍历
        Set<String> keySet = dataSource.keySet();
        for (String key: keySet) {
            if (dataSource.get(key).isSame(user)) {
                result = dataSource.get(key);
                break;
            }
        }
        return result;
    }

    @Override
    public User searchById(Long id) {
        return dataSource.get(id.toString());
    }
}
